﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using PwdMgr.CommonContract;
using PwdMgr.Utility.Exceptions;
using PwdMgr.PwdMgrService.DataService;
using PwdMgr.PwdMgrService.UserAuthentication;
using PwdMgrUI.ViewModels;
using PwdMgrUI.Objects;

namespace PwdMgrUI
{
    /// <summary>
    /// Interaction logic for Register.xaml
    /// </summary>
    public partial class RegisterWindow : Window
    {
        public RegisterWindow()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(RegisterWindow_Loaded);
        }

        void Btn_Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        void RegisterWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.btn_Cancel.Click += Btn_Cancel_Click;

            InitViewModel();
        }

        private void InitViewModel()
        {
            RegisterViewModel vm = new RegisterViewModel();
            vm.GetPassword = () =>
                {
                    return this.pbox_Pwd.Password;
                };
            vm.GetConfirmPassword = () =>
                {
                    return this.pbox_CfmPwd.Password;
                };
            vm.SetPassword = s =>
                {
                    this.pbox_Pwd.Password = s;
                };
            vm.SetConfirmPassword = s =>
                {
                    this.pbox_CfmPwd.Password = s;
                };
            vm.CommandFinished += CommandFinished;

            this.DataContext = vm;
        }

        void CommandFinished(object sender, CommandNotificationEventArgs e)
        {
            if (e.Result != CommandResult.Success)
            {
                Error(e.Errors.First().Value);
            }
            else
            {
                MessageBox.Show("Success!");
                this.Close();
            }
        }

        private void Error(string format, params object[] parameters)
        {
            MessageBox.Show(string.Format(format, parameters), "Error",
                MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }
}
